package games;

import gameUtils.Coordinate;
import gameUtils.GameMath;
import games.gameObjects.TDObject;
import games.gameObjects.towers.Tower;
import games.gameObjects.towers.Tower1;
import games.gameObjects.towers.Tower2;
import games.gameObjects.towers.Tower3;

import java.awt.Point;

public class Market {

	public static final double SALE_PERCENTAGE = 0.25;
	public static final int STARTING_BUDGET = 200;
	private int[] costs = {Tower1.COST, Tower2.COST, Tower3.COST};

	private int budget;
	private String key;
	private Coordinate mouse;


	public Market() {
		super();

		this.budget = STARTING_BUDGET;
	}

	public int getDifferentTypes(){
		return costs.length;
	}

	public int getBudget() {
		return budget;
	}

	public String getKey() {
		return key;
	}

	public void clear() {
		this.key = null;
		this.mouse = null;
	}

	public Coordinate getMouse() {
		return mouse;
	}

	public void addBudget(final double d){
		if(d < 0)
			throw new IllegalArgumentException("Budget can't be negative");

		this.budget += d;
	}

	public void setKey(final Integer keyInteger){
		if(keyInteger == null)
			throw new IllegalArgumentException("keyInteger can't be null");

		String selectedKey = GameMath.convertToString(keyInteger);
		if(canBuy(selectedKey))
			this.key = selectedKey;
	}

	public void setMouse(final Point mousePoint){
		if(mousePoint == null)
			throw new IllegalArgumentException("keyInteger can't be null");
		
		this.mouse = GameMath.convertToGameCoordinate(mousePoint);
	}

	public TDObject buyObject(){
		int index = Integer.parseInt(key);
		Tower [] towers = {new Tower1(mouse), new Tower2(mouse), new Tower3(mouse)};

		if(index >= towers.length)
			return null;

		return towers[index];
	}


	private boolean canBuy(final String key){
		assert(key != null);
		assert(!key.isEmpty());
		
		if(!GameMath.isNumber(key))
			return false;

		int index = Integer.parseInt(key);

		if(index >= costs.length)
			return false;

		return budget - costs[index] >= 0;
	}


	public void sellTower(final Tower sellingTower){
		if(sellingTower == null)
			throw new IllegalArgumentException("sellingTower can't be null");
		
		addBudget(sellingTower.getCost() * SALE_PERCENTAGE);
	}

	@Override
	public String toString() {
		return "Key="+(key == null ? "" : key + "") +
				"  Mouse="+(mouse == null ? "" : "[" + mouse.getAbcissa() + "," + mouse.getOrdinate() + "]")
				+ " Budget=" + budget;
	}

}
